package com.ejlchina.tool.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.ItemFirmwareUpgradeDeviceBinding
import com.ejlchina.tool.bean.BleDeviceBean

@SuppressLint("NotifyDataSetChanged")
class DeviceHeadAdapterIndexFix(
    private val dataList: List<BleDeviceBean>,
) : RecyclerView.Adapter<DeviceHeadAdapterIndexFix.PushRodParametersViewHolder>() {

    init {
        if (dataList.isNotEmpty()){
            dataList[0].isSelect = true
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PushRodParametersViewHolder {
        val binding = ItemFirmwareUpgradeDeviceBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return PushRodParametersViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: PushRodParametersViewHolder, position: Int) {
        holder.bind(dataList[position])
    }

    fun getSelectDeviceList() = dataList.filter { it.isSelect }

    inner class PushRodParametersViewHolder(
        private val binding: ItemFirmwareUpgradeDeviceBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bind(bleDevice: BleDeviceBean) {
            binding.tvIndex.text = "${bleDevice.bucketNo}#"
            binding.tvVersion.text = bleDevice.getDeviceNoString()
            setSelectBg(bleDevice.isSelect)
            binding.root.setOnClickListener {
                setSelectStateRadioAndMulti(bleDevice)
                notifyDataSetChanged()
            }
        }

        private fun setSelectStateRadioAndMulti(bleDevice: BleDeviceBean) {
            val howManySelectDevice = dataList.count { it.isSelect }
            val isTheOnlySelectIsThis = dataList.find { it.isSelect } == bleDevice
            val isClickTheOnlySelectDevice = howManySelectDevice == 1 && isTheOnlySelectIsThis
            if (!isClickTheOnlySelectDevice) {
                bleDevice.isSelect = !bleDevice.isSelect
            }
        }

        private fun setSelectBg(isSelect: Boolean) {
            val bgRes = if (isSelect) R.drawable.shape_co_8_so_f7f7f7_st_1f39ff else R.drawable.shape_co_8_so_ff3b30
            binding.root.setBackgroundResource(bgRes)
        }
    }
}